package com.blockmeta.bbs.minemodule.activity;

import android.content.Intent;
import android.graphics.Color;
import androidx.annotation.IdRes;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blockmeta.bbs.baselibrary.base.adapter.QuickPagerAdapter;
import com.blockmeta.bbs.baselibrary.net.callback.MyStringCallback;
import com.blockmeta.bbs.baselibrary.utils.CalculateUtil;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.StatusBarUtils;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterConstant;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.business.UmengEvent;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.decoration.GridSpaceDecoration;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.DialogUtil;
import com.blockmeta.bbs.businesslibrary.widget.CircleIndicator;
import com.blockmeta.bbs.minemodule.R;
import com.blockmeta.bbs.minemodule.R2;
import com.blockmeta.bbs.minemodule.adapter.GoldShopAdapter;
import com.blockmeta.bbs.minemodule.pojo.GoldShopPOJO;
import com.blockmeta.bbs.minemodule.pojo.GuaGuaKaPOJO;
import com.blockmeta.bbs.minemodule.widget.GuaGuaKa;
import com.blockmeta.bbs.minemodule.widget.PercentViewGamble;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author airthor
 * @date 2018 10 17
 * 金币商城
 */
@Route(path = RouterPath.COIN_MARKET_ACTIVITY,extras = RouterConstant.EXTRAL_LOGIN)
public class CoinMarketActivity extends BaseActivity implements View.OnClickListener{

    @BindView(R2.id.tv_title)
    TextView mTvTitle;
    @BindView(R2.id.btn_right)
    LinearLayout mBtnRight;
    @BindView(R2.id.vp_guide)
    ViewPager mVpGuide;
    @BindView(R2.id.flipper_lottery_winner)
    ViewFlipper mFlipperLotteryWinner;
    @BindView(R2.id.tv_prize)
    TextView mTvPrize;
    @BindView(R2.id.tv_play_again)
    TextView mTvPlayAgain;
    @BindView(R2.id.gua_gua_ka)
    GuaGuaKa mGuaGuaKa;
    @BindView(R2.id.btn_lottery_draw)
    Button mBtnLotteryDraw;
    @BindView(R2.id.tv_lottery_free)
    TextView mTvLotteryFree;
    @BindView(R2.id.ci_indicator)
    CircleIndicator mIndicator;
    @BindView(R2.id.tv_coin_count)
    TextView mTvCoinCount;
    @BindView(R2.id.rcv_exchange_list)
    RecyclerView mRcvExchangeList;

    private List<View> mViews = new ArrayList<>(5);
    private QuickPagerAdapter<View> mQuickPagerAdapter;
    private GoldShopAdapter mShopAdapter;
    private List<GoldShopPOJO.ConversionBean> grids = new ArrayList<>();
    private List<GoldShopPOJO.GambleBean> mGambleBeans;
    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        return getLayoutInflater().inflate(R.layout.activity_coin_market, null);
    }

    @Override
    public void setStatusBarColor() {
        StatusBarUtils.setDarkMode(this);
        StatusBarUtils.setWindowStatusBarColor(this,R.color.status_trans);
        StatusBarUtils.setWindowFullScreen(this);
    }

    @Override
    protected void initialize() {
        super.initialize();
        mTvTitle.setText("金币商城");
        mBtnRight.setVisibility(View.INVISIBLE);

        mQuickPagerAdapter = new QuickPagerAdapter<>(this, mViews);
        mVpGuide.setAdapter(mQuickPagerAdapter);

        mRcvExchangeList.setLayoutManager(new GridLayoutManager(this,2));
        mRcvExchangeList.addItemDecoration(new GridSpaceDecoration());
        mShopAdapter = new GoldShopAdapter(this,R.layout.item_gold_shop,grids);
        mRcvExchangeList.setAdapter(mShopAdapter);
        netWork();
    }

    private void netWork() {
        OkHttpUtils.get()
                .addHeader("token", SharedPreferenceUtil.getString(this, Constant.TOKEN,null))
                .addHeader("uid", AccountHelper.getUid())
                .url(NetConstant.GOLD_SHOP)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if(mTvCoinCount == null){
                            return;
                        }
                        GoldShopPOJO goldShopPOJO = new Gson().fromJson(response,GoldShopPOJO.class);
                        if (goldShopPOJO==null) {return;}
                        mTvCoinCount.setText(String.valueOf(goldShopPOJO.gold));
                        viewPagerFillData(goldShopPOJO);
                        flipperFillData(goldShopPOJO);
                        grids.addAll(goldShopPOJO.conversion);
                        mShopAdapter.notifyDataSetChanged();
                    }
                });
    }

    private void flipperFillData(GoldShopPOJO goldShopPOJO) {
        for (GoldShopPOJO.ScratchBean.ListBean bean : goldShopPOJO.scratch.list) {
            TextView textView = new TextView(CoinMarketActivity.this);
            textView.setTextColor(Color.WHITE);
            textView.setTextSize(14);
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setText(String.format(Locale.CHINESE,"恭喜 %s 刮出%d金币", bean.username, bean.award));
            mFlipperLotteryWinner.addView(textView,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }
        mFlipperLotteryWinner.startFlipping();
    }

    private void viewPagerFillData(GoldShopPOJO goldShopPOJO) {
        mGambleBeans = goldShopPOJO.gamble;
        for (GoldShopPOJO.GambleBean bean : goldShopPOJO.gamble) {
            View view = getLayoutInflater().inflate(R.layout.pager_up_down, null);
            ImageView icon = getView(view,R.id.iv_icon);
            if (!TextUtils.isEmpty(bean.iconUrl)){
                Picasso.with(CoinMarketActivity.this).load(bean.iconUrl).into(icon);
            }
            TextView title = getView(view,R.id.tv_title);
            title.setText(String.format("%s涨跌竞猜", bean.symbol));
            TextView timeRange = getView(view,R.id.tv_current_time);
            timeRange.setText(String.format("%s-%s", bean.start, bean.end));
            TextView cost = getView(view,R.id.tv_current_price);
            cost.setText(String.format(Locale.CHINESE,"投一次%d金币", bean.cost));
            ImageView ivUp = getView(view,R.id.iv_sup_left);
            ImageView ivDown = getView(view,R.id.iv_sup_right);
            ImageView btnUp = getView(view,R.id.btn_up);
            ImageView btnDown = getView(view,R.id.btn_down);
            PercentViewGamble percentViewGamble = getView(view,R.id.iv_up_down);
            double totalWeight = bean.up+bean.down;
            if (totalWeight != 0) {
                double percent = CalculateUtil.div(bean.up, totalWeight);
                percentViewGamble.setPercent((float) percent);
            }
            btnUp.setOnClickListener(CoinMarketActivity.this);
            btnDown.setOnClickListener(CoinMarketActivity.this);
            if (bean.select == 1){
                btnUp.setImageResource(R.drawable.btn_up_click);
                btnUp.setEnabled(false);
                btnDown.setEnabled(false);
                btnDown.setImageResource(R.drawable.btn_down_click);
                ivUp.setVisibility(View.VISIBLE);
            }else if (bean.select == 2){
                btnDown.setImageResource(R.drawable.btn_down_click);
                btnDown.setEnabled(false);
                btnUp.setEnabled(false);
                btnUp.setImageResource(R.drawable.btn_up_click);
                ivDown.setVisibility(View.VISIBLE);
            }
            mViews.add(view);
        }
        mQuickPagerAdapter.notifyDataSetChanged();
        mIndicator.setViewPager(mVpGuide);
    }

    //猜涨跌
    private void gamble(String symbol, final String select, final int position) {
        //umeng
        HashMap<String, String> map = new HashMap<>();
        map.put("coin_tyoe_ID",symbol);
        map.put("fcst_type_ID",select);
        UmengEvent.eventStatistics(this,Constant.U_MINE_goldshop_fcstbtn,map);

        OkHttpUtils.post()
                .addHeader("token", SharedPreferenceUtil.getString(this, Constant.TOKEN,null))
                .addHeader("uid", AccountHelper.getUid())
                .url(String.format(NetConstant.GAMBLE,symbol,select))
                .build()
                .execute(new MyStringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        GuaGuaKaPOJO object = new Gson().fromJson(response,GuaGuaKaPOJO.class);
                        int totalCoins = object.balance;
                        int award = object.award;
                        String message = object.message;
                        if (!TextUtils.isEmpty(message)){
                            ToastUtil.show(message);
                            return;
                        }
                        mTvCoinCount.setText(String.valueOf(totalCoins));

                        View view = mViews.get(position);
                        ImageView ivUp = getView(view,R.id.iv_sup_left);
                        ImageView ivDown = getView(view,R.id.iv_sup_right);
                        ImageView btnUp = getView(view,R.id.btn_up);
                        ImageView btnDown = getView(view,R.id.btn_down);
                        btnUp.setOnClickListener(CoinMarketActivity.this);
                        btnDown.setOnClickListener(CoinMarketActivity.this);
                        if ("1".equals(select)){
                            btnUp.setImageResource(R.drawable.btn_up_click);
                            btnUp.setEnabled(false);
                            btnDown.setEnabled(false);
                            ivUp.setVisibility(View.VISIBLE);
                        }else if ("2".equals(select)){
                            btnDown.setImageResource(R.drawable.btn_up_click);
                            btnDown.setEnabled(false);
                            btnUp.setEnabled(false);
                            ivDown.setVisibility(View.VISIBLE);
                        }
                    }
                });
    }
    //刮奖
    private void scratch(final boolean isAgain){
        OkHttpUtils.post()
                .addHeader("token", SharedPreferenceUtil.getString(this, Constant.TOKEN,null))
                .addHeader("uid", AccountHelper.getUid())
                .url(NetConstant.SCRATCH)
                .build()
                .execute(new MyStringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            GuaGuaKaPOJO object = new Gson().fromJson(response, GuaGuaKaPOJO.class);
                            int totalCoins = object.balance;
                            int award = object.award;
                            String message = object.message;
                            if (!TextUtils.isEmpty(message)){
                                ToastUtil.show(message);
                                return;
                            }
                            mTvPrize.setText(String.format(Locale.CHINESE,"恭喜中奖啦！%d金币 已入账", award));
                            mTvCoinCount.setText(String.valueOf(totalCoins));
                            if (isAgain){
                                mGuaGuaKa.reset();
                            }else {
                                mBtnLotteryDraw.setVisibility(View.GONE);
                                mTvLotteryFree.setVisibility(View.GONE);
                                mGuaGuaKa.setCanLotteryDraw(true);
                            }
                            if (object.num<=1){
                                UmengEvent.eventStatistics(CoinMarketActivity.this,Constant.U_MINE_goldshop_onemore,null);
                                return;
                            }
                            HashMap<String, String> map = new HashMap<>(2);
                            map.put("scratch_rank_ID",object.num+"");
                            UmengEvent.eventStatistics(CoinMarketActivity.this,Constant.U_MINE_goldshop_onemore,map);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    @OnClick({R2.id.btn_left, R2.id.btn_lottery_draw_again, R2.id.btn_lottery_draw,R2.id.btn_exchange_history,R2.id.iv_about})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.btn_left) {
            finish();

        } else if (i == R.id.btn_lottery_draw_again) {
            scratch(true);

        } else if (i == R.id.btn_lottery_draw) {
            scratch(false);

        } else if (i == R.id.btn_exchange_history) {
            //兑换记录
            Intent intent = new Intent(this, CoinGotDetailActivity.class);
            intent.putExtra("title", "兑换记录");
            intent.putExtra("url", NetConstant.CONVERSION_HISTORY);
            startActivity(intent);
            UmengEvent.eventStatistics(this, Constant.U_MINE_goldshop_change, null);

        } else if (i == R.id.iv_about) {
            //预测赢金币规则
            DialogUtil.showExplainDialog(this, R.layout.dialog_gamble_explain);
            UmengEvent.eventStatistics(this, Constant.U_MINE_goldshop_fcstrule, null);
        }
    }

    private  <T extends View> T getView(View views,@IdRes int viewId) {
        T view = null;
        if (views!=null){
            view=views.findViewById(viewId);
        }
        return view;
    }

    @Override
    public void onClick(View v) {
        int position = mVpGuide.getCurrentItem();
        int i = v.getId();
        if (i == R.id.btn_up) {
            gamble(mGambleBeans.get(position).symbol, "1", position);

        } else if (i == R.id.btn_down) {
            gamble(mGambleBeans.get(position).symbol, "2", position);
        }
    }
}
